package com.fuxinglianbao.services;

import com.fuxinglianbao.common.ApiResponse;
import com.fuxinglianbao.exception.BusinessException;
import com.fuxinglianbao.models.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class AuthService {
    @Autowired
    private UserService userService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public void sendVerificationCode(String phone) {
        // 发送验证码
        smsService.sendVerificationCode(phone);
    }

    @Transactional
    public User registerByPhone(String phone, String password, String code, String referrerPhone) {
        // 验证手机号格式
        if (!isValidPhone(phone)) {
            throw new BusinessException("手机号格式不正确");
        }

        // 验证验证码
        if (!smsService.verifyCode(phone, code)) {
            throw new BusinessException("验证码错误或已过期");
        }

        // 验证密码强度
        if (!isValidPassword(password)) {
            throw new BusinessException("密码必须包含数字和字母，长度在6-20位之间");
        }

        // 注册用户
        return userService.register(phone, password, referrerPhone);
    }

    @Transactional
    public User loginByPassword(String phone, String password) {
        if (!isValidPhone(phone)) {
            throw new BusinessException("手机号格式不正确");
        }

        return userService.login(phone, password);
    }

    @Transactional
    public User loginByCode(String phone, String code) {
        if (!isValidPhone(phone)) {
            throw new BusinessException("手机号格式不正确");
        }

        // 验证验证码
        if (!smsService.verifyCode(phone, code)) {
            throw new BusinessException("验证码错误或已过期");
        }

        // 获取用户信息，如果用户不存在则自动注册
        User user = userService.findByPhone(phone);
        if (user == null) {
            // 生成随机密码（用户可以后续修改）
            String randomPassword = generateRandomPassword();
            user = userService.register(phone, randomPassword, null);
        }

        // 更新登录时间
        user.setLastLoginTime(LocalDateTime.now());
        return user;
    }

    private boolean isValidPhone(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }

    private boolean isValidPassword(String password) {
        return password != null && 
               password.length() >= 6 && 
               password.length() <= 20 && 
               password.matches(".*[0-9].*") && 
               password.matches(".*[a-zA-Z].*");
    }

    private String generateRandomPassword() {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < 12; i++) {
            password.append(chars.charAt((int) (Math.random() * chars.length())));
        }
        return password.toString();
    }
}